package com.tchy.cloud.controller;


import com.tchy.cloud.entity.*;
import com.tchy.cloud.exception.SysAccountExistException;
import com.tchy.cloud.service.AConsultantService;
import com.tchy.cloud.tools.sms.SendSMSForIhuyi;
import jodd.bean.BeanUtil;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.service.CommonService;
import org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil;
import org.jeecgframework.core.util.MutiLangUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.TSSYSConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by xiaoji on 2017/2/20.
 */
@Controller
@RequestMapping("/consultantController")
public class AConsultantController {
    private static final Logger logger = Logger.getLogger(AConsultantController.class.getName());
    @Autowired
    private CommonService commonService;

    @Autowired
    private AConsultantService aConsultantService;

    /**
     * 咨询师跳转
     *
     * @return
     */
    @RequestMapping(params = "view")
    public ModelAndView view() {
        return new ModelAndView("clound/consultant/view");
    }

    /**
     * 咨询师课程系列页面跳转
     *
     * @return
     */
    @RequestMapping(params = "courseSeriesIndex")
    public ModelAndView courseSeriesIndex() {
        return new ModelAndView("clound/consultant/courseSeriesIndex");
    }

    /**
     * 跳转咨询师选择页面---单选
     *
     * @return
     */
    @RequestMapping(params = "selectConsultantView")
    public ModelAndView selectConsultantView() {
        return new ModelAndView("clound/consultant/selectConsultantView");
    }

    /**
     * 工作室咨询师管理页面跳转
     *
     * @param id
     * @param req
     * @return
     */
    @RequestMapping(params = "stuPersonManager")
    public ModelAndView ad(String id, HttpServletRequest req) {
        req.setAttribute("id", id);
        return new ModelAndView("clound/consultant/stuPersonManager");
    }


    /**
     * 变更工作室内咨询师的等级
     *
     * @param req
     * @return
     */
    @RequestMapping(params = "setLevel")
    public ModelAndView setLevel(HttpServletRequest req) {
        String id = req.getParameter("id");
        AStudioConsultantEntity entity = commonService.getEntity(AStudioConsultantEntity.class, Long.valueOf(id));
        req.setAttribute("entity", entity);
        return new ModelAndView("clound/consultant/setLevel");
    }

    /**
     * 工作室人员信息
     *
     * @param entity
     * @param request
     * @param response
     * @param dataGrid
     */
    @RequestMapping(params = "stuPersonGrid")
    public void datagrid(AStudioConsultantEntity entity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        String id = request.getParameter("id");
        CriteriaQuery cq = new CriteriaQuery(AStudioConsultantEntity.class, dataGrid);
        cq.eq("studioId", Long.valueOf(id));
        String realname = request.getParameter("consultantEntity.aCustomerEntity.realname");
        if (StringUtil.isNotEmpty(realname)) {
            cq.createAlias("consultantEntity.aCustomerEntity", "as_entity");
            cq.like("as_entity.realname", '%' + realname + '%');
            entity.getConsultantEntity().getaCustomerEntity().setRealname(null);
        }

        cq.addOrder("studioConsultantId", SortDirection.desc);
        cq.add();
        // 查询条件组装
        HqlGenerateUtil.installHql(cq, entity, request.getParameterMap());
        commonService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 获取咨询师列表
     *
     * @param aConsultantEntity 咨询师对象
     * @param request
     * @param response
     * @param dataGrid
     */
    @RequestMapping(params = "datagrid")
    public void datagrid(AConsultantEntity aConsultantEntity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(AConsultantEntity.class, dataGrid);
        cq.addOrder("consultantId", SortDirection.desc);
        cq.add();
        // 查询条件组装
        HqlGenerateUtil.installHql(cq, aConsultantEntity, request.getParameterMap());
        commonService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }


    /**
     * 获取咨询师列表
     *
     * @param aConsultantEntity 过滤过的咨询师对象
     * @param request
     * @param response
     * @param dataGrid
     */
    @RequestMapping(params = "datagridFilter")
    public void datagridFilter(AConsultantEntity aConsultantEntity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(AConsultantEntity.class, dataGrid);
        cq.addOrder("consultantId", SortDirection.desc);
        cq.add();
        // 查询条件组装
        HqlGenerateUtil.installHql(cq, aConsultantEntity, request.getParameterMap());
        commonService.getDataGridReturn(cq, true);
//        String studioId = request.getParameter("studioId");
//        List list = cq.getResults();
//        for (int i = 0; i < list.size(); i++) {
//            AConsultantEntity entity = (AConsultantEntity) list.get(i);
//            Long conId = entity.getConsultantId();
//            List<Map<String, Object>> resultList = commonService.findForJdbc("select * from a_studio_consultant where studio_id = ? and consultant_id = ?", new Object[]{Long.valueOf(studioId), conId});
//            if (resultList.size() > 0)
//                list.remove(entity);
//        }
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 添加 咨询师到工作室
     *
     * @param req request
     * @return 处理结果信息
     */
    @RequestMapping(params = "addConsultantToStudio")
    @ResponseBody
    public AjaxJson addConsultantToStudio(HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        String sql = "insert a_studio_consultant values(null,?,?,3,now())";
        try {
            String studioId = req.getParameter("studioId");
            String userIds = req.getParameter("userIds");

            String sql1 = "select t1.consultant_id as conid from a_studio_consultant t1 where t1.studio_id =? and t1.consultant_id = ?";

            String[] conId = userIds.split(",");
            for (int i = 0; i < conId.length; i++) {
                List<Map<String, Object>> list = commonService.findForJdbc(sql1, new Object[]{studioId,conId[i]});
                if (list.size() > 0) {

                } else {
                    commonService.executeSql(sql, new Object[]{studioId, conId[i]});
                }
            }
            j.setMsg("操作成功");
        } catch (
                Exception e
                )

        {
            e.printStackTrace();
            logger.error(e);
            j.setSuccess(false);
            j.setMsg("操作失败");
        }

        return j;
    }


    /**
     * 更新工作室中咨询师的等级
     *
     * @param entity
     * @param req
     * @return
     */
    @RequestMapping(params = "upLevel")
    @ResponseBody
    public AjaxJson upLevel(AStudioConsultantEntity entity, HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        try {
            AStudioConsultantEntity p = commonService.getEntity(AStudioConsultantEntity.class, entity.getStudioConsultantId());
            if (entity.getLevel() == 1) {
                List<Map<String, Object>> list = commonService.findForJdbc("select * from a_studio_consultant where studio_id = ? and level=?", new Object[]{p.getStudioId(), 1});
                if (list.size() > 0) {
                    j.setMsg("工作室只允许一个首席专家，请勿重复添加。");
                } else {
                    MyBeanUtils.copyBeanNotNull2Bean(entity, p);
                    commonService.saveOrUpdate(p);
                    j.setMsg("操作成功");
                }
            } else {
                MyBeanUtils.copyBeanNotNull2Bean(entity, p);
                commonService.saveOrUpdate(p);
                j.setMsg("操作成功");
            }
        } catch (Exception e) {
            logger.error(e);
            j.setSuccess(false);
            j.setMsg("操作失败");
        }
        return j;
    }

    /**
     * 虚拟列realname 供回调展示
     *
     * @param aConsultantEntity
     * @param request
     * @param response
     * @param dataGrid
     */
    @RequestMapping(params = "datagrid2")
    public void datagrid2(AConsultantEntity aConsultantEntity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(AConsultantEntity.class, dataGrid);
        cq.addOrder("consultantId", SortDirection.desc);
        cq.add();
        // 查询条件组装
        HqlGenerateUtil.installHql(cq, aConsultantEntity, request.getParameterMap());
        commonService.getDataGridReturn(cq, true);
        DataGrid dg = cq.getDataGrid();
        dataGrid = this.getDataGrid(dg);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 虚拟字段赋值
     */
    private DataGrid getDataGrid(DataGrid dg) {
        List list = dg.getResults();
        for (int i = 0; i < list.size(); i++) {
            AConsultantEntity consultantEntity = (AConsultantEntity) list.get(i);
            consultantEntity.setRealName(consultantEntity.getaCustomerEntity().getRealname());
        }
        return dg;
    }

    /**
     * 跳转到新增或者修改界面
     *
     * @param aConsultantEntity
     * @param req
     * @return
     */
    @RequestMapping(params = "addorupdateView")
    public ModelAndView addorupdateView(AConsultantEntity aConsultantEntity, HttpServletRequest req) {
        if (aConsultantEntity.getConsultantId() != null) {
            aConsultantEntity = commonService.getEntity(AConsultantEntity.class, aConsultantEntity.getConsultantId());
        }
        req.setAttribute("consultant", aConsultantEntity);
        List<AAuthEntity> aAuthEntities = commonService.findByProperty(AAuthEntity.class, "consultantId", aConsultantEntity.getConsultantId());
        if (aAuthEntities.size() > 0) {
            for (int i = 0; i < aAuthEntities.size(); i++) {
                AAuthEntity aAuthEntity = aAuthEntities.get(i);
                int index = i + 1;
                req.setAttribute("auth" + index, aAuthEntity.getImage());
            }
        }

        String second_classes = aConsultantEntity.getSecondClasses();
        if (!StringUtil.isEmpty(second_classes)) {
            second_classes = StringUtil.changeStringDouHao(second_classes);
            if(!StringUtil.isEmpty(second_classes)){
                String sql = "select * from a_columns where columns_id in(" + second_classes + ")";
                List<Map<String, Object>> list = commonService.findForJdbc(sql);
                req.setAttribute("secondClassesTag", list);
            }
        }

        return new ModelAndView("clound/consultant/addorupdateView");
    }

    /**
     * 添加保存咨询师
     *
     * @param aConsultantEntity
     * @return
     */
    @RequestMapping(params = "saveorupdate", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson saveorupdate(AConsultantEntity aConsultantEntity, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            if (aConsultantEntity.getConsultantId() != null) {
                //修改咨询师
                AConsultantEntity entity = commonService.getEntity(AConsultantEntity.class, aConsultantEntity.getConsultantId());
                MyBeanUtils.copyBeanNotNull2Bean(aConsultantEntity, entity);
                commonService.saveOrUpdate(entity);
                //修改用户
                ACustomerEntity aCustomerEntity = commonService.getEntity(ACustomerEntity.class, aConsultantEntity.getConsultantId());
                MyBeanUtils.copyBeanNotNull2Bean(entity.getaCustomerEntity(), aCustomerEntity);
                commonService.saveOrUpdate(aCustomerEntity);
                //认证图片
                aConsultantService.addAuth(request, aConsultantEntity.getConsultantId());
            } else {
                //保存咨询师和用户信息
                aConsultantService.saveAConsultant(aConsultantEntity, request);
            }
            j.setMsg("操作成功");
        } catch (SysAccountExistException e) {
            logger.error(e);
            j.setSuccess(false);
            j.setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
            j.setSuccess(false);
            j.setMsg("操作失败");
        }
        return j;
    }

    /**
     * 添加认证图片
     *
     * @param request      请求对象
     * @param consultantId 咨询师地址
     */
    public void addAuth(HttpServletRequest request, Long consultantId) {
        String auth1 = request.getParameter("auth1");
        String auth2 = request.getParameter("auth2");
        String auth3 = request.getParameter("auth3");
        String auth4 = request.getParameter("auth4");
        String auth5 = request.getParameter("auth5");
        List<AAuthEntity> aAuthEntities = commonService.findByProperty(AAuthEntity.class, "consultantId", consultantId);
        String sql = "delete from a_auth where consultant_id=?";
        commonService.executeSql(sql, new Object[]{consultantId});
        addSingleAuth(auth1, consultantId);
        addSingleAuth(auth2, consultantId);
        addSingleAuth(auth3, consultantId);
        addSingleAuth(auth4, consultantId);
        addSingleAuth(auth5, consultantId);
    }

    /**
     * 添加单个图片
     *
     * @param path
     */
    public void addSingleAuth(String path, Long consultantId) {
        if (!StringUtil.isEmpty(path)) {
            AAuthEntity aAuthEntity = new AAuthEntity();
            aAuthEntity.setConsultantId(consultantId);
            aAuthEntity.setImage(path);
            aAuthEntity.setUploadTime(new Date());
            commonService.save(aAuthEntity);
        }
    }

    /**
     * /**
     * 标签页面跳转
     *
     * @return
     */
    @RequestMapping(params = "secondClasses")
    public ModelAndView secondClasses(String ids, String upiframename, HttpServletRequest req) {
        req.setAttribute("ids", ids);
        List<AColumnsEntity> aColumnsEntities = commonService.findByQueryString("FROM AColumnsEntity");
        req.setAttribute("aColumnsEntities", aColumnsEntities);
        req.setAttribute("upiframename", upiframename);
        return new ModelAndView("clound/consultant/secondClasses");
    }

    /**
     * 设置为首页推荐
     *
     * @param aConsultantEntity 咨询师对象
     * @param req
     * @return
     */
    @RequestMapping(params = "recomm")
    @ResponseBody
    public AjaxJson recomm(AConsultantEntity aConsultantEntity, HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        try {
            AConsultantEntity aConsultantEntity2 = commonService.getEntity(AConsultantEntity.class, aConsultantEntity.getConsultantId());
            aConsultantEntity2.setIsRecomm(aConsultantEntity.getIsRecomm());
            commonService.save(aConsultantEntity2);
            j.setMsg("设置成功");
        } catch (Exception e) {
            logger.error(e);
            j.setSuccess(false);
            j.setMsg("设置失败");
        }
        return j;
    }


    /**
     * 删除工作室中的咨询师
     */
    @RequestMapping(params = "delStuPerson")
    @ResponseBody
    public AjaxJson delStuPerson(AStudioConsultantEntity entity, HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        try {
            String id = req.getParameter("id");
            if (null != id) {
                entity = commonService.getEntity(AStudioConsultantEntity.class, Long.valueOf(id));
                commonService.delete(entity);
                j.setMsg("操作成功");
            } else {
                j.setMsg("咨询师不存在，请重试。");
            }
        } catch (Exception e) {
            logger.error(e);
            j.setSuccess(false);
            j.setMsg("操作失败");
        }
        return j;
    }

    /**
     * 工作室新增咨询师列表页面跳转
     *
     * @return
     */
    @RequestMapping(params = "consultandList")
    public ModelAndView addStuPerson(HttpServletRequest req) {
        String id = req.getParameter("id");//   工作室id
        req.setAttribute("studioId", id);
        return new ModelAndView("clound/consultant/consultantList");
    }

    /**
     * 设置为专家
     *
     * @param aConsultantEntity 咨询师对象
     * @param req
     * @return
     */
    @RequestMapping(params = "expert")
    @ResponseBody
    public AjaxJson expert(AConsultantEntity aConsultantEntity, HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        try {
            AConsultantEntity aConsultantEntity2 = commonService.getEntity(AConsultantEntity.class, aConsultantEntity.getConsultantId());
            aConsultantEntity2.setIsExpert(aConsultantEntity.getIsExpert());
            commonService.save(aConsultantEntity2);
            j.setMsg("设置成功");
        } catch (Exception e) {
            logger.error(e);
            j.setSuccess(false);
            j.setMsg("设置失败");
        }
        return j;
    }

    /**
     * 审核页面跳转
     *
     * @return
     */
    @RequestMapping(params = "authView")
    public ModelAndView authView(AConsultantEntity aConsultantEntity, HttpServletRequest req) {
        AConsultantEntity aConsultantEntity2 = commonService.getEntity(AConsultantEntity.class, aConsultantEntity.getConsultantId());
        req.setAttribute("consultant", aConsultantEntity2);
        return new ModelAndView("clound/consultant/authView");
    }

    /**
     * 审核页面跳转
     *
     * @return
     */
    @RequestMapping(params = "expertView")
    public ModelAndView expertView(AConsultantEntity aConsultantEntity, HttpServletRequest req) {
        AConsultantEntity aConsultantEntity2 = commonService.getEntity(AConsultantEntity.class, aConsultantEntity.getConsultantId());
        req.setAttribute("consultant", aConsultantEntity2);
        return new ModelAndView("clound/consultant/expertView");
    }

    /**
     * 咨询师查看
     *
     * @param aConsultantEntity 咨询师对象
     * @param req
     * @return
     */
    @RequestMapping(params = "previewView")
    public ModelAndView previewView(AConsultantEntity aConsultantEntity, HttpServletRequest req) {
        if (aConsultantEntity.getConsultantId() != null) {
            aConsultantEntity = commonService.getEntity(AConsultantEntity.class, aConsultantEntity.getConsultantId());
        }
        req.setAttribute("consultant", aConsultantEntity);
        List<AAuthEntity> aAuthEntities = commonService.findByProperty(AAuthEntity.class, "consultantId", aConsultantEntity.getConsultantId());

        if (aAuthEntities.size() > 0) {
            for (int i = 0; i < aAuthEntities.size(); i++) {
                AAuthEntity aAuthEntity = aAuthEntities.get(i);
                int index = i + 1;
                req.setAttribute("auth" + index, aAuthEntity.getImage());
            }
        }

        String second_classes = aConsultantEntity.getSecondClasses();
        if (!StringUtil.isEmpty(second_classes)) {
            second_classes = StringUtil.changeStringDouHao(second_classes);
            if (!StringUtil.isEmpty(second_classes)) {
                String sql = "select * from a_columns where columns_id in(" + second_classes + ")";
                List<Map<String, Object>> list = commonService.findForJdbc(sql);
                req.setAttribute("secondClassesTag", list);
            }
        }
        return new ModelAndView("clound/consultant/preview");
    }

    /**
     * 审核结果
     *
     * @param aConsultantEntity
     * @param req
     * @return
     */
    @RequestMapping(params = "auth")
    @ResponseBody
    public AjaxJson auth(AConsultantEntity aConsultantEntity, HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        try {
            AConsultantEntity aConsultantEntity2 = commonService.getEntity(AConsultantEntity.class, aConsultantEntity.getConsultantId());
            aConsultantEntity2.setIsAuth(aConsultantEntity.getIsAuth());

            int isAuth = aConsultantEntity.getIsAuth().intValue();
            String phone = aConsultantEntity2.getaCustomerEntity().getPhone();
            String realname = aConsultantEntity2.getaCustomerEntity().getRealname();
            int sex = aConsultantEntity2.getaCustomerEntity().getSex();
            if (sex == 0) {
                realname += "先生";
            } else if (sex == 0) {
                realname += "女士";
            }
            if (isAuth == 1) {//认证成功发短信通知
                String successMsg = "尊敬的" + realname + ",恭喜您在心询心的咨询师资料认证已通过，请使用手机号码登录，开启愉快的心询之旅吧";
                SendSMSForIhuyi.sendContent(phone, successMsg);
            } else if (isAuth == 2) {//认证失败发短信通知
                TSSYSConfig tssysConfig = commonService.getEntity(TSSYSConfig.class, "10004");
                String failMsg = "尊敬的" + realname + ",抱歉您在心询心的咨询师资料认证未通过审核,请联系平台客服：" + tssysConfig.getConfig() + "。";
                SendSMSForIhuyi.sendContent(phone, failMsg);
            }
            commonService.save(aConsultantEntity2);
            j.setMsg("设置成功");
        } catch (Exception e) {
            logger.error(e);
            j.setSuccess(false);
            j.setMsg("设置失败");
        }
        return j;
    }

}
